import mapconfig from '@/config/config_map.js'
import load from '@/utils/jsapi.js';
import mapModelColorGet from '@/utils/maputils/mapModelColorGet.js'

function parseXml(xmlData) {
  //解析查询结果
  var resultDataset = [];
  var dz_result = xmlData.children[0]
  if (dz_result.children.length > 0) {
    var result_flag = dz_result.children[0].innerHTML.slice(0, 1)
    var newDataset = dz_result.children[1].children[1].children[0]
    // console.log(newDataset)
    var tables = newDataset.children
    var len = tables.length
    for (var i = 0; i < len; i++) {
      var tab = tables[i]
      let attributes = tab.children
      var item = {};
      for (var j = 0; j < attributes.length; j++) {
        var attr = attributes[j];
        var key = attr.nodeName;
        item[key.toLowerCase()] = attr.innerHTML;
      }
      resultDataset.push(item);
    }
  }
  return resultDataset;
}

const addresslocationsearch = {

    async dosearch(searchtext) {
      const [
        esriRequest,
        Point,
        SpatialReference,
        FeatureLayer,
        LabelClass,
        Graphic,
        Camera
      ] = await load([
        'esri/request',
        'esri/geometry/Point',
        'esri/geometry/SpatialReference',
        'esri/layers/FeatureLayer',
        'esri/layers/support/LabelClass',
        'esri/Graphic',
        'esri/Camera'
      ])

      const options = {
        responseType: 'xml'
      }
      $('.esri-addresslocation-search-content').empty()

      let graphicsource = []
      const simrenderer = {
        type: "simple", // autocasts as new SimpleRenderer()
        symbol: {
          type: "text", // autocasts as new TextSymbol()
          color: "#7A003C",
          text: "\ue61d", // esri-icon-map-pin
          font: {
            // autocasts as new Font()
            size: 24,
            family: "CalciteWebCoreIcons"
          }
        }
      }
      const popupTemplate = {
        title: '{name}',
        content: [{
          type: 'fields',
          fieldInfos: [{
              fieldName: 'name',
              label: '名称'
            },
            {
              fieldName: 'REGION_QX',
              label: '区县'
            }, {
              fieldName: 'CLS',
              label: '类型'
            }
          ]
        }]
      }
      const fieldJsonArray = [{
          name: 'OBJECTID',
          alias: 'OBJECTID',
          type: 'oid'
        },
        {
          name: 'name',
          alias: '名称',
          type: 'string'
        },
        {
          name: 'REGION_QX',
          alias: '区县',
          type: 'string'
        }, {
          name: 'CLS',
          alias: '类型',
          type: 'string'
        }
      ]



      // const url = mapconfigshare.proxyConifg.url + '?http://map.smi.sh.cegn.cn/OneMapServer/rest/services/address/as_ch.asmx/ASCH_AddressSearch?vSearch_word=' + searchtext + '&vSearch_class=&vSearch_region=&vSearch_year=&vResult_count=100&token=' + window.maptoken
      const url = mapconfig.locationaddress.url + searchtext + '&vSearch_class=&vSearch_region=&vSearch_year=&vResult_count=100&token=' + window.addresstoken
      esriRequest(url, options).then(function (response) {
          const resultData = parseXml(response.data)
          if (resultData == null || resultData.length === 0) {
            $('.esri-addresslocation-search-content').empty()
          } else {
            resultData.map(function (item, ary, index) {
              let locationaddressdiv = ''
              locationaddressdiv += '<div class="locationaddress" data-entityType="' + item.point_x + '|' + item.point_y + '">'
              locationaddressdiv += '<span class="esri-icon-map-pin locationaddress-image">'
              locationaddressdiv += '</span>'
              locationaddressdiv += '<div class="locationaddress-text">'
              locationaddressdiv += '<span class="location-poi">' + item.poi + '</span>'
              locationaddressdiv += '<span class="location-qx">' + item.region_qx + '</span>'
              locationaddressdiv += '</div>'
              // + item.poi + '</div>'
              locationaddressdiv += '</div>'

              $('.esri-addresslocation-search-content').append(locationaddressdiv)

              const point = new Point({
                x: item.point_x,
                y: item.point_y,
                spatialReference: SpatialReference.WebMercator
              });

              const PointGraphic = new Graphic({
                geometry: point,
                attributes: {
                  name: item.poi,
                  cls: item.cls,
                  region_qx: item.region_qx
                }
              });
              graphicsource.push(PointGraphic);
            })

            let addresslocationgraphiclayer = window.map.findLayerById('addresslocationgraphiclayer')
            if (addresslocationgraphiclayer === undefined || addresslocationgraphiclayer === null) {
              addresslocationgraphiclayer = new FeatureLayer({
                id: 'addresslocationgraphiclayer',
                title: 'addresslocationgraphiclayer',
                objectIdField: 'OBJECTID',
                geometryType: 'point',
                renderer: simrenderer,
                screenSizePerspectiveEnabled: true,
                popupEnabled: true,
                popupTemplate: popupTemplate,
                fields: fieldJsonArray,
                listMode: 'show',
                elevationInfo: 'relative-to-scene',
                spatialReference: SpatialReference.WebMercator,
                source: graphicsource
              })
              window.map.add(addresslocationgraphiclayer)
            } else {
              //   addresslocationgraphiclayer.source.removeAll()
              //   addresslocationgraphiclayer.source.addMany(graphicsource)
              addresslocationgraphiclayer.source = graphicsource
              addresslocationgraphiclayer.refresh()
            }

            var statesLabelClass = new LabelClass({
              labelExpressionInfo: {
                expression: "$feature.NAME"
              },
              symbol: {
                type: "text",
                color: mapModelColorGet.fontforeColor(),
                haloSize: 2,
                haloColor: mapModelColorGet.basemapmodelColor() 
              },
              labelPlacement: "above-center"
            });
            addresslocationgraphiclayer.labelingInfo = [statesLabelClass];
            if (graphicsource.length > 0)
              window.sceneView.goTo(graphicsource);

            $('.locationaddress').delegate('span', 'click', function (e) {
                const enitytype = $(this).parents('.locationaddress').data('entitytype')
                $(this).parents('.locationaddress').addClass('active')
                $(this).parents('.locationaddress').siblings().removeClass('active')
                const cordxy = enitytype.split('|')
                let point = new Point({
                  x: parseFloat(cordxy[0]),
                  y: parseFloat(cordxy[1]),
                  spatialReference: SpatialReference.WebMercator
                });
                const hightsymbol = {
                  type: "text", // autocasts as new TextSymbol()
                  color: "#DC143C",
                  text: "\ue61d", // esri-icon-map-pin
                  font: {
                    // autocasts as new Font()
                    size: 28,
                    family: "CalciteWebCoreIcons"
                  }
                }

                  let PointGraphic = new Graphic({
                    geometry: point,
                    symbol: hightsymbol
                  })

                  let Airport_Hightlight = window.map.findLayerById('Airport_Hightlight')   
                  if (Airport_Hightlight != null && Airport_Hightlight != undefined){
                    window.map.reorder(Airport_Hightlight, window.map.layers.length+2)
                    Airport_Hightlight.removeAll();
                    Airport_Hightlight.add(PointGraphic)
                    window.sceneView.goTo([PointGraphic])
                  }
                })
            }
          })
      }
    }
    export default addresslocationsearch
